/**
 * @author xiaobyu
 * @created Mar 25, 2016
 * 
 */
package nconv.convert.generator;

import java.util.ArrayList;
import java.util.List;

import nconv.convert.ConvertUtils;
import nconv.convert.BaseWordConverter;
import org.apache.poi.hwpf.HWPFDocumentCore;
import org.apache.poi.hwpf.usermodel.Bookmark;
import org.apache.poi.hwpf.usermodel.CharacterRun;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;
import org.w3c.dom.Element;

public class ImageInfoGenerator extends BaseWordConverter {

	public static void main(String[] args) throws Exception {
		ConvertUtils.process("FD007890.doc", new ImageInfoGenerator());
		ConvertUtils.process("29215-d40.doc", new ImageInfoGenerator());
	}
	
	private static final String BOOKMARK = "bookmark";

	@Override
	protected void processParagraph(HWPFDocumentCore wordDocument, Element parentElement, int currentTableLevel,
	    Paragraph paragraph, String bulletText) {
		Element pElement = textDocumentFacade.createParagraph();
		processCharacters( wordDocument, currentTableLevel, paragraph, pElement );
		parentElement.appendChild(pElement);
		parentElement.appendChild(textDocumentFacade.createText("\n"));
	}
	
	protected void outputCharacters(Element block, CharacterRun characterRun,
      String text) {
		boolean inBookmark = false;
		Element e = block;
		while (e != null) {
			if (e.hasAttribute(BOOKMARK)) {
				inBookmark = true;
				break;
			}
			e = (Element)e.getParentNode();
		}
		if (inBookmark)
			block.appendChild(textDocumentFacade.createText(text));
  }
	
	protected void processBookmarks(HWPFDocumentCore wordDocument, Element currentBlock, Range range,
	    int currentTableLevel, List<Bookmark> rangeBookmarks) {
		Element parent = currentBlock;
		List<Element> eles = new ArrayList<>();
		for (Bookmark bm : rangeBookmarks) {
			Element e = textDocumentFacade.createBlock();
			e.setAttribute(BOOKMARK, "yes");
			e.appendChild(textDocumentFacade.createText("<div id='" + bm.getName() + "'>"));
			eles.add(e);
			parent.appendChild(e);
			parent = e;
		}
		
		if (range != null) {
			processCharacters(wordDocument, currentTableLevel, range, parent);
		}
		for (Element ele : eles) {
			ele.appendChild(textDocumentFacade.createText("</div>"));
		}
		
	}
}